<template>
  <el-form 
    ref="formRef" 
    :model="form" 
    :rules="rules" 
    label-width="100px"
    class="medicine-form"
  >
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="form-section-title">基本信息</div>
      </el-col>
      <el-col :span="12">
        <el-form-item label="药品名称" prop="medicineName">
          <el-input v-model="form.medicineName" placeholder="请输入药品名称" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="药品规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入药品规格" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="剂型" prop="dosageForm">
          <el-input v-model="form.dosageForm" placeholder="请输入剂型" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="批准文号" prop="approvalNumber">
          <el-input v-model="form.approvalNumber" placeholder="请输入批准文号" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="生产厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入生产厂家" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="保质期(月)" prop="shelfLife">
          <el-input-number 
            v-model="form.shelfLife" 
            :min="1" 
            :max="120"
            :precision="0"
            controls-position="right"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="储存条件" prop="storageCondition">
          <el-input v-model="form.storageCondition" placeholder="请输入储存条件" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <div class="form-section-title">分类信息</div>
      </el-col>
      <el-col :span="12">
        <el-form-item label="通用分类" prop="commonCategoryId">
          <el-select v-model="form.commonCategoryId" placeholder="请选择通用分类">
            <el-option
              v-for="item in commonCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="处方类型" prop="prescriptionCategoryId">
          <el-select v-model="form.prescriptionCategoryId" placeholder="请选择处方类型">
            <el-option
              v-for="item in prescriptionCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <div class="form-section-title">详细信息</div>
      </el-col>
      <el-col :span="12">
        <el-form-item label="单价" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="库存数量" prop="salesVolume">
          <el-input-number 
            v-model="form.salesVolume" 
            :min="0"
            :precision="0"
            controls-position="right"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="药品图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/medicine/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="药品成分" prop="ingredients">
          <el-input v-model="form.ingredients" type="textarea" :rows="3" placeholder="请输入药品成分" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="适应症" prop="indications">
          <el-input v-model="form.indications" type="textarea" :rows="3" placeholder="请输入适应症" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="禁忌症" prop="contraindications">
          <el-input v-model="form.contraindications" type="textarea" :rows="3" placeholder="请输入禁忌症" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="用法用量" prop="usageMethod">
          <el-input v-model="form.usageMethod" type="textarea" :rows="3" placeholder="请输入用法用量" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="注意事项" prop="precautionNotes">
          <el-input v-model="form.precautionNotes" type="textarea" :rows="3" placeholder="请输入注意事项" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCommonCategories, getPrescriptionCategories } from '../../../api/medicine'

const props = defineProps({
  formData: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: 'add'
  }
})

const form = reactive({
  medicineId: null,
  medicineName: '',
  specification: '',
  dosageForm: '',
  approvalNumber: '',
  manufacturer: '',
  shelfLife: undefined,
  storageCondition: '',
  ingredients: '',
  indications: '',
  contraindications: '',
  commonCategoryId: undefined,
  prescriptionCategoryId: undefined,
  salesVolume: undefined,
  price: undefined,
  imageUrl: '',
  usageMethod: '',
  precautionNotes: '',
  sideEffectDescriptions: '',
  drugInteractionDetails: ''
})

const formRef = ref(null)

// 分类选项
const commonCategoryOptions = ref([])
const prescriptionCategoryOptions = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    const [commonRes, prescriptionRes] = await Promise.all([
      getCommonCategories(),
      getPrescriptionCategories()
    ])

    if (commonRes.code === 200) {
      commonCategoryOptions.value = commonRes.data.map(item => ({
        id: item.id,
        name: item.name
      }))
    }

    if (prescriptionRes.code === 200) {
      prescriptionCategoryOptions.value = prescriptionRes.data.map(item => ({
        id: item.id,
        name: item.name
      }))
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

// 监听 formData 变化，实现编辑时的数据回显
watch(
  () => props.formData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 深拷贝防止互相影响
      const formData = JSON.parse(JSON.stringify(newVal))
      Object.assign(form, formData)
    }
  },
  { immediate: true, deep: true }
)

// 表单验证规则
const rules = {
  medicineName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  specification: [{ required: true, message: '请输入药品规格', trigger: 'blur' }],
  dosageForm: [{ required: true, message: '请输入剂型', trigger: 'blur' }],
  approvalNumber: [{ required: true, message: '请输入批准文号', trigger: 'blur' }],
  manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
  shelfLife: [{ required: true, message: '请输入保质期', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0, message: '单价必须大于0', trigger: 'blur' }
  ],
  commonCategoryId: [{ required: true, message: '请选择通用分类', trigger: 'change' }],
  prescriptionCategoryId: [{ required: true, message: '请选择处方类型', trigger: 'change' }]
}

// 图片上传相关方法
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    form.imageUrl = response.data
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 表单验证方法
const validate = async () => {
  if (!formRef.value) return Promise.reject('表单实例不存在')
  try {
    await formRef.value.validate()
    return Promise.resolve(form)
  } catch (error) {
    return Promise.reject(error)
  }
}

// 在组件挂载时获取分类数据
onMounted(() => {
  fetchCategories()
})

defineExpose({
  validate,
  form
})
</script>

<style lang="scss" scoped>
.medicine-form {
  padding: 20px;
  
  .form-section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin: 16px 0;
    padding-left: 10px;
    border-left: 4px solid var(--el-color-primary);
    line-height: 1;
  }
  
  .el-form-item {
    margin-bottom: 22px;
  }
  
  .el-input-number {
    width: 100%;
  }
  
  .avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    transition: all 0.3s;
    
    &:hover {
      border-color: var(--el-color-primary);
      transform: translateY(-2px);
    }
    
    .avatar {
      border-radius: 8px;
    }
  }
}
</style>
